<template>
  <div class="sku-list">
    <table
      :border="false"
      fit
      style="width: 100%;"
    >
      <thead>
      <tr>
        <th
          v-for="(th, thi) in skuLabel"
          :key="thi"
          :colspan="th.colspan"
          :rowspan="th.rowspan"
        >
          {{th.name}}
        </th>
      </tr>
      <tr>
        <th
          v-for="(th, thi) in skuName"
          :key="thi"
        >
          {{th}}
        </th>
      </tr>
      </thead>
      <tbody>
      <tr
        v-for="(item, index) in list"
        :key="index"
      >
        <td
          v-for="(o, i) in item.sku"
          :key="i"
        >
          {{ o.value }}
        </td>
        <td>
          <div class="my_upload">
            <div class="demo-image__lazy" v-if="item.imageList && item.imageList.length > 0">
              <el-image :src="item.imageList[0].url" lazy :fit="'cover'" :preview-src-list="[item.imageList[0].url]">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                  <i class="el-upload-list__item-delete"></i>
                </div>
              </el-image>
            </div>
            <el-upload
              :action="url"
              :headers="headers"
              :on-success="onSuccess"
              :limit="1"
              v-if="currentUpload !== item._id"
            >
              <i slot="default" class="el-icon-plus" @click="currentId=item._id" />
            </el-upload>
          </div>
        </td>
        <td>
          <el-input v-model="item.price" />
        </td>
        <td>
          <el-input v-model="item.cost" />
        </td>
        <td>
          <el-input v-model="item.stock" />
        </td>
        <td>
          <el-input v-model="item.sort" />
        </td>
        <td>
          <el-switch v-model="item.status" />
        </td>
        <td v-if="false">
          <el-input v-model="item.sn" />
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { sortSku } from '@/utils/sku'
import api from '@/api'
export default {
  props: ['product'],
  computed: {
    headers() {
      return {
        [process.env.VUE_APP_TOKEN]: getToken()
      }
    },
    skuName() {
      // console.log(this.skuNameList)
      return this.product.skuName.map(x => x.name)
      // return [
      //   '颜色',
      //   '尺码',
      //   '大小',
      // ]
    },
    // 这个没有用， 因为在组件中, 不能绑定数据更新操作
    skuList() {
      // const rs = sortSku(this.sku)
      const list = this.skuNameList.map(x => x.value)
      const rs = sortSku(list)
      // console.log(sortSku(this.sku), rs)
      // console.log(rs.map(item => {
      //   return {
      //     sku: item,
      //     image: '',
      //     price: 0,
      //     cost: 0,
      //     stock: 0,
      //     sort: 0,
      //     status: 1,
      //     sn: ''
      //   }
      // }))
      return rs.map(item => {
        return {
          sku: item,
          image: '',
          price: 0,
          cost: 0,
          stock: 0,
          sort: 0,
          status: true,
          // sn: ''
        }
      })
    },
    skuLabel() {
      const length = this.product.skuName.map(x => x.name).length
      return [
        {
          name: '商品规格',
          // colspan: this.sku.length,
          colspan: length,
          rowspan: length > 0 ? 1 : 2
        },
        {
          name: '图片',
          rowspan: 2
        },
        {
          name: '价格',
          rowspan: 2
        },
        {
          name: '成本',
          rowspan: 2
        },
        {
          name: '库存',
          rowspan: 2
        },
        {
          name: '排序',
          rowspan: 2
        },
        {
          name: '状态',
          rowspan: 2
        },
        // {
        //   name: '编码',
        //   rowspan: 2
        // }
      ]
    }
  },
  data() {
    return {
      // sku: [
      //   [
      //     { value: '绿色' },
      //     { value: '白色' },
      //     { value: '红色' },
      //   ],
      //   [
      //     { value: 'S'},
      //     { value: 'M'},
      //     { value: 'L'},
      //   ],
      //   [
      //     { value: '大' },
      //     { value: '中' },
      //     { value: '小' },
      //   ]
      // ],
      list: [],
      x: [],
      // 图片相关
      url: `${process.env.VUE_APP_BASE_API}/api/upload/execute?env=${process.env.NODE_ENV}&width=750&height=750&quality=100&bucket=supplier_category&max-width=750`,
      currentId: 0,
      currentUpload: 0,
      // 是否为新生成的sku列表
      count: 0
    }
  },
  watch: {
    list: {
      deep: true,
      handler(v) {
        // console.log(v)
        this.$emit('change', v)
      }
    }
  },
  methods: {
    action() {
      const x = [...this.product.skuName]
      const list = x.map(x => x.values)
      const rs = sortSku(list)
      this.list = rs.map(item => {
        return {
          sku: item,
          image: '',
          price: this.product.price,
          cost: 0,
          stock: this.product.stock,
          sort: 0,
          status: true,
          sn: '',
          // 把值设置成唯一ID
          _id: item.map(x => x.id).join('|')
        }
      })
      // 编辑的数据, 把数据赋值过来
      this.product.sku.forEach(x => {
        this.list.forEach(y => {
          if (y._id === x.sku_list) {
            this.count += 1
            this.$set(y, 'price', x.price)
            this.$set(y, 'cost', x.self_cost)
            this.$set(y, 'sort', x.sort)
            this.$set(y, 'stock', x.stock)
            // this.$set(y, 'sn', x.sn)
            this.$set(y, 'status', +x.status === 1)
            // 图片
            if (x.image) {
              this.$set(y, 'imageList', [{
                id: +x.image.id,
                url: x.image.thumbnail_path
              }])
            } else {
              this.$set(y, 'imageList', [])
            }
          }
        })
      })
      // console.log(this.list)
    },
    onSuccess(response, file, fileList) {
      // console.log(response)
      api.sku.skuImage({
        id: this.currentId,
        image_id: response.data.id,
        product_id: this.product.id
      }).then(() => {
        this.list.forEach(x => {
          if (x._id === this.currentId) {
            this.$set(x, 'imageList', [{
              id: +response.data.id,
              url: response.data.thumbnail
            }])
            this.$set(x, 'image', +response.data.id)
            // console.log(x)
          }
        })
        // 刷新
        this.$message({
          message: '上传成功',
          type: 'success',
          duration: 1 * 1000
        })
        // 解决刷新问题
        this.currentUpload = this.currentId
        // this.$router.push(`/product/sku/${this.product.id}`)
        setTimeout(() => {
          this.currentUpload = 0
        }, 5)
      })
    },
  },
  created() {
    this.action()
  }
}
</script>

<style scoped lang="scss">
.sku-list {
  table {
    border: none;
  }
  td, th {
    border: 1px solid #cbcbcb;
    padding: 5px 10px;
    margin: 0;
    min-width: 120px;
  }
}
.my_upload {
  display: flex;
  justify-content: center;
  align-items: center;
  .demo-image__lazy {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
  }
}
</style>
